package org.jks.controller;

import java.io.File;
import java.util.Date;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.jks.constant.Constants;
import org.jks.constant.SysConfig;
import org.jks.model.Attachment;
import org.jks.model.AttachmentType;
import org.jks.model.User;
import org.jks.response.model.ActionResult;
import org.jks.response.model.UITable;
import org.jks.service.AttachmentService;
import org.jks.service.AttachmentTypeService;
import org.jks.util.FileUtil;
import org.jks.util.OSUtil;
import org.jks.util.ResponseUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;

@Controller
@RequestMapping("/attachment")
public class AttachmentController {
	@Autowired
	AttachmentService attachmentService;
	@Autowired
	AttachmentTypeService attachmentTypeService;
	
	@RequestMapping("/createfolder")
	public void createFolder(@RequestParam String base, @RequestParam String name, HttpServletRequest request, HttpSession session,
			HttpServletResponse response){
		ActionResult ar = new ActionResult();
		if(base.equals("\\") && OSUtil.isLinux()){
			base = "/";
		}
		if(name.length() > 0){
			User user = (User) session.getAttribute(Constants.SESSION_ACCOUNT);
			if(user == null){
				ar.setMsg("用户没登录");
			}
			else{
				String basePath = request.getServletContext().getRealPath("/") + File.separator + SysConfig.ATTACHEMENT + File.separator + SysConfig.MATERIAL; 
				String path = "";
				if(user.getFlight() != null){
					path = basePath + File.separator + user.getFlight().getName();
				}
				else{
					path = basePath + File.separator + "admin-flight";
				}
				
				String folderPath = "";
				if(!base.equals("\\") && base.length() > 0){
					folderPath += base;
				}
				folderPath += File.separator + name;
				path += folderPath;
				if(!FileUtil.isExist(path)){
					FileUtil.createFolder(path);
					Attachment workAttachment = new Attachment();
					workAttachment.setFileType(1);
					workAttachment.setAddTime(new Date());
					workAttachment.setFlight(user.getFlight());
					workAttachment.setName(name);
					workAttachment.setPath(folderPath);
					AttachmentType type = attachmentTypeService.findByName(SysConfig.BANZU_ATTACHMENT_TYPE_DEFAULT);
					workAttachment.setType(type);
					try {
						attachmentService.save(workAttachment);
						ar.setSuccess(true);
					} catch (Exception e) {
						ar.setMsg(e.getMessage());
						e.printStackTrace();
					}
				}
				else{
					ar.setMsg("目录已经存在"); 
				}
			}
		}
		else{
			ar.setMsg("参数不正确");
		}
		ResponseUtil.returnJson(response, ar);
	}

	@RequestMapping("/add")
	public void add(@RequestParam(value = "file") MultipartFile file, @RequestParam String base, HttpServletRequest request, HttpSession session,
			HttpServletResponse response) {
		ActionResult ar = new ActionResult();
		if(base.equals("\\") && OSUtil.isLinux()){
			base = "/";
		}
		User user = (User) session.getAttribute(Constants.SESSION_ACCOUNT);
		if(user == null){
			ar.setMsg("您还没登录，请先登录再上传文件");
		}
		else{
			String filename = file.getOriginalFilename();
			String basePath = request.getServletContext().getRealPath("/") + File.separator + SysConfig.ATTACHEMENT + File.separator + SysConfig.MATERIAL; 
			String path = "";
			if(user.getFlight() != null){
				path = basePath + File.separator + user.getFlight().getName();
			}
			else{
				path = basePath + File.separator + "admin-flight";
			}
			
			String folderPath = "";
			if(base.length() > 0){
				folderPath += base;
			}
			folderPath += File.separator + filename;
			path += folderPath;
			FileUtil.copyFile(file, path);
			Attachment workAttachment = new Attachment();
			workAttachment.setFileType(0);
			workAttachment.setAddTime(new Date());
			workAttachment.setFlight(user.getFlight());
			workAttachment.setName(filename);
			workAttachment.setPath(folderPath);
			AttachmentType type = attachmentTypeService.findByName(SysConfig.BANZU_ATTACHMENT_TYPE_DEFAULT);
			workAttachment.setType(type);
			try {
				attachmentService.save(workAttachment);
				ar.setSuccess(true);
			} catch (Exception e) {
				ar.setMsg(e.getMessage());
				e.printStackTrace();
			}
		}
		ResponseUtil.returnJson(response, ar);
	}
	
	@RequestMapping("/update")
	public void update(Attachment workAttachment, HttpServletRequest request, HttpServletResponse response){
		try{
			attachmentService.update(workAttachment);
		}
		catch(Exception e){
			e.printStackTrace();
		}
	}
	
	@RequestMapping("/list")
	public void list(@RequestParam String path, HttpServletRequest request, HttpServletResponse response, HttpSession session){
		ActionResult ar = new ActionResult();
		try{
			List<Attachment> workAttachments = null;
			User user = (User) session.getAttribute(Constants.SESSION_ACCOUNT);
			if(path.equals("\\") && OSUtil.isLinux()){
				path = "/";
			}
			session.setAttribute(Constants.SESSION_ZL_PATH, path);
			workAttachments = attachmentService.list(user.getFlight(), path);
			
			ar.setSuccess(true);
			UITable table = new UITable();
			table.setRows(workAttachments);
			ar.setData(table);
		}
		catch(Exception e){
			e.printStackTrace();
		}
		ResponseUtil.returnJson(response, ar);
	}
	
	@RequestMapping("/query")
	public void query(@RequestParam String filename, HttpServletRequest request, HttpServletResponse response, HttpSession session){
		ActionResult ar = new ActionResult();
		try{
			List<Attachment> workAttachments = null;
			User user = (User) session.getAttribute(Constants.SESSION_ACCOUNT);
			workAttachments = attachmentService.query(user.getFlight(), filename);
			
			ar.setSuccess(true);
			UITable table = new UITable();
			table.setRows(workAttachments);
			ar.setData(table);
		}
		catch(Exception e){
			e.printStackTrace();
		}
		ResponseUtil.returnJson(response, ar);
	}
	
	@RequestMapping("/download/{filename}.{fex}")
	public void download(@PathVariable String filename, @PathVariable String fex, @RequestParam String filepath,HttpServletRequest request, HttpServletResponse response, HttpSession session){
		String basePath = request.getServletContext().getRealPath("/");
		String base = (String) session.getAttribute(Constants.SESSION_ZL_PATH);
		if(base.equals("\\") && OSUtil.isLinux()){
			base = "/";
		}
		basePath = basePath + File.separator + SysConfig.ATTACHEMENT;
		filename = filename + "." + fex;
		basePath = basePath + File.separator + SysConfig.MATERIAL;
		User user = (User) session.getAttribute(Constants.SESSION_ACCOUNT);
		
		if(user != null){
			String path = "";
			if(user.getFlight() != null){
				path = basePath + File.separator + user.getFlight().getName();
			}
			else{
				path = basePath + File.separator + "admin-flight";
			}
			path += filepath;
			FileUtil.download(path,  filename, response);
		}
	}
	
	
	
	@RequestMapping("/delete/{id}")
	public void delete(@PathVariable long id,HttpServletRequest request, HttpSession session, HttpServletResponse response){
		ActionResult ar = new ActionResult();
		Attachment attachment = attachmentService.findById(id);
		String basePath = request.getServletContext().getRealPath("/");
		basePath = basePath + File.separator + SysConfig.ATTACHEMENT;
		basePath = basePath + File.separator + SysConfig.MATERIAL;
		User user = (User) session.getAttribute(Constants.SESSION_ACCOUNT);
		
		if(user != null){
			String path = "";
			if(user.getFlight() != null){
				path = basePath + File.separator + user.getFlight().getName();
			}
			else{
				path = basePath + File.separator + "admin-flight";
			}
			
			path += attachment.getPath();
			FileUtil.delete(path);
			attachmentService.delete(user.getFlight(), attachment.getPath());
			ar.setSuccess(true);
		}
		if(!ar.isSuccess()){
			ar.setMsg("删除失败");
		}
		ResponseUtil.returnJson(response, ar);
	}
}
